import lejos.nxt.*;
import lejos.nxt.comm.*;
import lejos.robotics.navigation.DifferentialPilot;
import java.io.*;

/**
 * Handles the Bluetooth connection to the server.
 * @author bjorn, kristian, robert
 * 
 */
public class BTConnection {

	private DataInputStream dis;
	private DataOutputStream dos;
	lejos.nxt.comm.NXTConnection btc;

	/**
	 * Waits for a connection to be established to the robot.
	 */
	public void waitForConnection() {

		LCDDisplay.print("WaitFConnection");

		btc = Bluetooth.waitForConnection();

		Sound.playTone(440, 400, 75);
		Sound.playTone(350, 800, 75);
		
		LCDDisplay.print("Connected.");

		dis = btc.openDataInputStream();
		dos = btc.openDataOutputStream();

	}

	/**
	 * Adds the data to the output buffer.
	 * @param data
	 * @throws IOException
	 */
	public void addToBuffer(String data) throws IOException {
		dos.writeUTF(data);
	}

	/**
	 * Sends everything in the output buffer.
	 * @throws IOException
	 */
	public void flush() throws IOException {
		dos.flush();
	}

	/**
	 * Adds data to the output buffer and sends the whole buffer.
	 * @param data
	 * @throws IOException
	 */
	public void send(String data) throws IOException {
		dos.writeUTF(data);
		dos.flush();
	}

	/**
	 * Closes the Bluetooth connection.
	 * @throws IOException
	 */
	public void close() throws IOException {
		

		Sound.playTone(350, 400, 75);
		Sound.playTone(440, 800, 75);
		
		dis.close();
		dos.close();
		btc.close();
	}

	/**
	 * Returns everything in the input buffer.
	 * @return dataString
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public String recieveData() throws IOException, InterruptedException {
		LCDDisplay.print("** Listening...");
		StringBuilder buffer = new StringBuilder();

		while (buffer.length() == 0) {
			Thread.sleep(500);
			buffer.append(dis.readUTF().trim());
		}

		return buffer.toString();
	}
}
